//
//  ChildVC.swift
//  placepic
//
//  Created by 이유진 on 2020/07/02.
//  Copyright © 2020 elesahich. All rights reserved.
//

import UIKit
import Kingfisher
import XLPagerTabStrip
import Alamofire

extension Notification.Name {
    static let changeChildViewVC = Notification.Name("changechildviewVC")
}

//placeDetailVC
class ChildVC: UIViewController, IndicatorInfoProvider {
    
    @IBOutlet weak var placeListTV: UITableView!
    @IBOutlet weak var sumNum: UILabel!

    var childNumber: String = ""
    var placeList: placeListClass?
    var placeListData: [placeData] = []
    
    var frame: CGRect!
    var keyword: [Int] = []
    var useful: [Int] = []
    var currentIdx = 0
    
// MARK: - View LifeCycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavigationBar()
        addObserver()
        setupTableViewDelegate()
        removeUserDefaults()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
                
        placeListTV.reloadData()
        checkCurrentPage()
        NotificationCenter.default.post(name: .changeChildViewVC, object: nil, userInfo: ["childNumber": childNumber])

    }
    

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if let index = placeListTV.indexPathForSelectedRow {
            placeListTV.deselectRow(at: index, animated: true)
        }
        

    }
}

// MARK:- 서버통신
extension ChildVC {
    
    private func checkCurrentPage() {
        currentIdx = CategoryIndex(rawValue: childNumber)?.index ?? -1
        if currentIdx == 0 {
            defaultCategoryData()
        } else {
            getEachCategoryData()
        }
    }
    // 전체, 필터링 X
    private func defaultCategoryData() {
        placeService.shared.getAllPlaces(0, [], []) { data in
            if let metaData = data {
                let LargeData = metaData
                guard let datum = LargeData.result else { return }
                self.placeListData = datum
                self.placeListTV.reloadData()
                self.sumNum.text = "총 \(self.placeListData.count)개 결과"
            }
        }
    }
    // 전체 X, 필터링 X
    private func getEachCategoryData() {
        placeService.shared.getPlaces(currentIdx, [], []) { data in
            if let metaData = data {
                let LargeData = metaData
                guard let datum = LargeData.result else { return }
                self.placeListData = datum
                self.placeListTV.reloadData()
                self.sumNum.text = "총 \(self.placeListData.count)개 결과"
            }
        }
    }

    @objc
    private func keywordNotification(_ notification: NSNotification) {
        guard let injectedModel = notification.userInfo?["indexPath.item"] as? [Int] else { return }
        keyword = injectedModel
//        print(#function)
        print("keyword: \(keyword)")
        
        let defaults = UserDefaults.standard
        defaults.set(keyword, forKey: "keyword")
        placeService.shared.getSelectedPlaces(currentIdx) { data in
            if let metaData = data {
                let LargeData = metaData
                guard let datum = LargeData.result else { return }
                self.placeListData = datum
                self.placeListTV.reloadData()
                self.sumNum.text = "총 \(self.placeListData.count)개 결과"
            }
        }
    }
    
    @objc
    private func usefulNotification(_ notification: NSNotification) {
        guard let injectedModel = notification.userInfo?["indexPath.item"]
            as? [Int] else { return }
        useful = injectedModel
        print("useful: \(useful)")
        
        let defaults = UserDefaults.standard
        defaults.set(useful, forKey: "useful")
        
        placeService.shared.getSelectedPlaces(currentIdx) { data in
            if let metaData = data {
                let LargeData = metaData
                guard let datum = LargeData.result else { return }
                self.placeListData = datum
                self.placeListTV.reloadData()
                self.sumNum.text = "총 \(self.placeListData.count)개 결과"
            }
        }
    }
    
    @objc
    private func subwayNotification(_ notification: NSNotification) {
        guard let injectedModel = notification.userInfo?["model"] as? [SubwayData] else { return }
        let subwayIndexArray = injectedModel.map { Int($0.subwayIdx ?? 0) }
        let defaults = UserDefaults.standard
        defaults.set(subwayIndexArray, forKey: "subway")
        
        placeService.shared.getSelectedPlaces(currentIdx) { data in
            if let metaData = data {
                let LargeData = metaData
                guard let datum = LargeData.result else { return }
                self.placeListData = datum
                self.placeListTV.reloadData()
                self.sumNum.text = "총 \(self.placeListData.count)개 결과"
            }
        }
    }
}

// MARK:- Navigation, Notifications
extension ChildVC {
    
    func addObserver() {
        NotificationCenter.default.addObserver(self, selector: #selector(keywordNotification), name: .homeModalKeywordNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(usefulNotification(_:)), name: .homeModalUsefulNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(subwayNotification), name: .searchSubwayNotification, object: nil)
    }
    
    func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
        return IndicatorInfo(title: "\(childNumber)")
    }
    
    func textFieldDidChange(sender: UITextField) {
        sender.invalidateIntrinsicContentSize()
    }
    
    private func setNavigationBar() {
        guard let navigationBar = self.navigationController?.navigationBar else { return }
        
        navigationBar.isTranslucent = true
        navigationBar.backgroundColor = UIColor.clear
        navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        navigationBar.shadowImage = UIImage()
        
        let leftButton: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "backArrowIc"),
                                                          style: .plain,
                                                          target: self,
                                                          action: #selector(dismissVC))
        navigationItem.leftBarButtonItem = leftButton
    }
    
    @objc private func dismissVC() {
        navigationController?.popViewController(animated: true)
    }
       
}

// MARK: - TableView
extension ChildVC: UITableViewDelegate, UITableViewDataSource{

    private func removeUserDefaults() {
        let defaults = UserDefaults.standard
        defaults.set([], forKey: "keyword")
        defaults.set([], forKey: "useful")
        defaults.set([], forKey: "subway")
    }
    
    private func setupTableViewDelegate() {
        placeListTV.delegate = self
        placeListTV.dataSource = self
        placeListTV.separatorStyle = .none
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return placeListData.count
    }
    
    private func hideTabBar() {
        frame = self.tabBarController?.tabBar.frame
        let height = frame.size.height
        frame?.origin.y = self.view.frame.size.height + (height)*10
        
        UIView.animate(withDuration: 0.3, animations: {
            self.tabBarController?.tabBar.frame = self.frame!
        })
    }
    
    //placeDetailVC
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
        if segue.identifier == "toDetailVC" {
            if let destination = segue.destination as? placeDetailVC {
                if let selectedIndex = self.placeListTV.indexPathsForSelectedRows?.first?.row {
                    destination.selectIdx = placeListData[selectedIndex].placeIdx
                }
            }
        }
    }
    

    func sizeHeaderToFit(tableView: UITableView) {
        if let headerView = placeListTV.tableHeaderView {
            let height = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
            var frame = headerView.frame
            frame.size.height = height
            headerView.frame = frame
            tableView.tableHeaderView = headerView
            headerView.setNeedsLayout()
            headerView.layoutIfNeeded()
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let placeListCell = tableView.dequeueReusableCell(withIdentifier: PlaceListTVC.identifier, for: indexPath) as? PlaceListTVC else { return UITableViewCell() }
        
        var dataInfo: String = ""
        var subwayInfo: String = ""
        
        guard let subway = placeListData[indexPath.row].subway else {
            return UITableViewCell()
        }
        
        if subway.count != 0 {
            subwayInfo = subway
                .map() { $0.subwayName ?? "" }
                .reduce("") { $0 + "/" + $1 }
                .trimmingCharacters(in: ["/"])
        }
        
        let date:Date = Date(timeIntervalSince1970: TimeInterval(placeListData[indexPath.row].placeCreatedAt!))
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy.MM.dd"
        
        if placeListData[indexPath.row].tag?.count == 0 {
            dataInfo = dataInfo + dateFormatter.string(from: date)
        } else {
            dataInfo = dataInfo + " · " + dateFormatter.string(from: date)
        }
        
        var tags:[String] = []
        for i in 0..<placeListData[indexPath.row].tag!.count{
            tags.append((placeListData[indexPath.row].tag?[i].tagName)!)
        }
        
        if tags.count == 0 {
            placeListCell.setPlaceInfo(pName: placeListData[indexPath.row].placeName!, pSubway: subwayInfo, pDate: dataInfo, pPhoto: (placeListData[indexPath.row].imageURL?[0])!, pWriter: (placeListData[indexPath.row].user?.profileURL)!, wName: (placeListData[indexPath.row].user?.userName)!, pTag1: "", pTag2: "", pTag3: "")
            placeListCell.placeTag[0].isHidden = true
            placeListCell.placeTag[1].isHidden = true
            placeListCell.placeTag[2].isHidden = true
        }
        else if tags.count == 1 {
            placeListCell.setPlaceInfo(pName: placeListData[indexPath.row].placeName!, pSubway: subwayInfo, pDate: dataInfo, pPhoto: (placeListData[indexPath.row].imageURL?[0])!, pWriter: (placeListData[indexPath.row].user?.profileURL)!, wName: (placeListData[indexPath.row].user?.userName)!, pTag1: tags[0], pTag2: "", pTag3: "")
            placeListCell.placeTag[1].isHidden = true
            placeListCell.placeTag[2].isHidden = true
        }
        else if tags.count == 2 {
            placeListCell.setPlaceInfo(pName: placeListData[indexPath.row].placeName!, pSubway: subwayInfo, pDate: dataInfo, pPhoto: (placeListData[indexPath.row].imageURL?[0])!, pWriter: (placeListData[indexPath.row].user?.profileURL)!, wName: (placeListData[indexPath.row].user?.userName)!, pTag1: tags[0], pTag2: tags[1], pTag3: "")
            placeListCell.placeTag[2].isHidden = true
        }
        else if tags.count > 2 {
            placeListCell.setPlaceInfo(pName: placeListData[indexPath.row].placeName!, pSubway: subwayInfo, pDate: dataInfo, pPhoto: (placeListData[indexPath.row].imageURL?[0])!, pWriter: (placeListData[indexPath.row].user?.profileURL)!, wName: (placeListData[indexPath.row].user?.userName)!, pTag1: tags[0], pTag2: tags[1], pTag3: "...")
        }
        return placeListCell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 125
    }
}

